package com.amgl.mobike.base;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amgl.mobike.app.IImageLoader;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 阿木 on 2017/2/21.
 */

public abstract class BaseRVAdapter<D> extends RecyclerView.Adapter<BaseViewHolder<D>> {

    private Context mContext;
    private LayoutInflater mLayoutInflater;
    private IImageLoader mImageLoader;

    private final List<D> mDataList = new ArrayList<>();

    public BaseRVAdapter(Context context, IImageLoader imageLoader) {
        mContext = context;
        mLayoutInflater = LayoutInflater.from(context);
        mImageLoader = imageLoader;
    }

    public void setDataList(List<D> dataList) {
        mDataList.clear();
        if (dataList != null) {
            mDataList.addAll(dataList);
        }
    }

    public void clearDataList() {
        mDataList.clear();
    }

    public List<D> getDataList() {
        return mDataList;
    }

    public void addDataList(List<D> dataList) {
        if (dataList != null) {
            mDataList.addAll(dataList);
        }
    }

    public void insertDataList(List<D> dataList) {
        if (dataList != null) {
            List<D> list = new ArrayList<>();
            list.addAll(dataList);
            list.addAll(mDataList);
            mDataList.clear();
            mDataList.addAll(list);
        }
    }

    @Override
    public int getItemCount() {
        if (mDataList != null) {
            return mDataList.size();
        }
        return 0;
    }

    @Override
    public void onBindViewHolder(BaseViewHolder<D> holder, int position) {
        D data = getItem(position);
        if (data != null) {
            holder.bindData(data, position);
        }
    }

    public D getItem(int position) {
        if (getItemCount() > position) {
            return mDataList.get(position);
        }
        return null;
    }

    public D getLastItem() {
        if (getItemCount() > 0)
            return mDataList.get(getItemCount() - 1);
        else
            return null;
    }

    protected View createItemView(int layoutId, ViewGroup parent) {
        return LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false);
    }

    protected Context getContext() {
        return mContext;
    }

    protected IImageLoader getImageLoader() {
        return mImageLoader;
    }
}
